package codeRandomThoughts.Test117填充每个节点的下一个右侧节点指针II;


import java.util.LinkedList;
import java.util.Queue;

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};

class Solution {
    public Node connect(Node root) {
        Node node = root;
        Node tem = new Node();
        int size;
        if (node == null) {
            return node;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.offer(node);

        while (!queue.isEmpty()) {
            size = queue.size();

            //node一开始是每层的第一个节点
            node = queue.peek();
            while (size > 0) {
                //目前的节点
                tem = queue.poll();
                if (node != tem) {//不处理每层的第一项
                    node.next = tem;
                }
                node = tem;

                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
        }
        return root;

    }
}